﻿using System.Collections.Generic;
using System.Linq;

using NPOI.SS.UserModel;

namespace Acl.Data.RowReaders
{
    internal class ExcelRowReader : IRowReader
    {
        private readonly ISheet _worksheet;
        private readonly int _startColumnNumber;
        private readonly int? _lastColumnNumber;

        private int _currentRowNumber;

        public string Name { get; private set; }
        public int? RowSize { get; private set; }

        public ExcelRowReader(string fileName, ISheet worksheet, uint startRowNumber, uint startColumnNumber, uint? columnSize = null, int? rowSize = null)
        {
            Name = fileName + ":" + worksheet.SheetName;
            _worksheet = worksheet;
            _currentRowNumber = (int)(startRowNumber - 1);
            _startColumnNumber = (int)(startColumnNumber - 1);

            if (columnSize.HasValue)
            {
                _lastColumnNumber = (int)(_startColumnNumber + columnSize - 1);
            }

            this.RowSize = rowSize;
        }

        public IList<string> Read()
        {
            var row = _worksheet.GetRow(_currentRowNumber);
            if (row == null)
                return null;
            List<string> result = [];

            for (var cellIndex = row.FirstCellNum; cellIndex < row.LastCellNum; cellIndex++)
            {
                ICell cell = row.GetCell(cellIndex);
                if (cell != null)
                {
                    if (FilterColumn(cell))
                    {
                        result.Add(cell.ToString());
                    }
                }
                else
                {
                    result.Add(string.Empty);
                }
            }

            _currentRowNumber++;

            if (RowSize == null)
            {
                if (result.Count > 0 && result.All(f => string.IsNullOrWhiteSpace(f)))
                    return null;
            }

            return result;
        }

        private bool FilterColumn(ICell cell)
        {
            if (cell.ColumnIndex < _startColumnNumber) return false;

            if (_lastColumnNumber.HasValue)
                return cell.ColumnIndex <= _lastColumnNumber;

            return true;
        }
    }
}